package com.bkgy.component;

import com.bkgy.jobs.HourTaskJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * 为了加快服务启动速度，将耗时长的服务放到启动后执行
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StartUpAfterComponent implements CommandLineRunner {
    @Value("${memcache.ip}")
    private String ip;
    @Value("${memcache.port}")
    private int port;
    @Value("${local_flag}")
    private boolean local_flag;

    private MemcachedClient client = null;

    @Override
    public void run(String... args) throws Exception {
        //本地环境不执行此逻辑（耗时长，影响测试）
        if (!local_flag) {
            try {
                client = new MemcachedClient(AddrUtil.getAddresses(ip + ":" + port));
            } catch (IOException e) {
                log.error("初始化Memcached客户端失败 ", e);
            }

        }
        //初始化系统启动月份和年份，用于跨月和跨年更新产量
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        HourTaskJob.oldMonth = cal.get(Calendar.MONTH);
        HourTaskJob.oldYear = cal.get(Calendar.YEAR);
    }

    public MemcachedClient getClient() {
        if (client == null) {
            try {
                client = new MemcachedClient(AddrUtil.getAddresses(ip + ":" + port));
            } catch (IOException e) {
                log.error("初始化Memcached客户端失败 ", e);
            }
        }
        return client;
    }
}
